const fse = require('fs-extra');
const path = require('path');
const entrys = require('./lib/entrys');
const rules = require('./lib/rules');
const plugins = require('./lib/plugins');
const resolve = require('./lib/resolve');
const { paths } = require('../utils');
const { webpackConfig, webpackPrdConfig } = require('./lib/config');

module.exports = () => {
  process.env.mode = process.env.mode || 'production';
  if (webpackPrdConfig) {
    return webpackPrdConfig;
  }
  const configPlugins = plugins({
    dll: webpackConfig.dll,
    sendSourceMap: webpackConfig.sendSourceMap
  });

  if(webpackConfig.sendSourceMap){
    fse.emptyDirSync(paths.sourcemapAsset);
  }

  return {
    mode: 'production',
    entry: entrys(webpackConfig.entry),
    output: {
      path: paths.prdPath,
      filename: 'js/[name].[chunkhash:8].js',
      chunkFilename: 'js/chunks/[name].[chunkhash:8].js',
      publicPath: paths.publicPath,
      sourceMapFilename: path.join(path.relative(paths.prdPath, paths.sourcemapAsset), paths.version, '[file].map'),
      ...webpackConfig.output
    },
    devtool: webpackConfig.devtool,
    stats: {
      assets: true,
      cachedAssets: false,
      errors: true,
      chunks: true,
      warningsFilter: warning => /Conflicting order between/gm.test(warning)
    },
    performance: {
      hints: false,
      assetFilter(assetFilename) {
        return !(/^static\/.*\.js$/.test(assetFilename));
      }
    },
    module: {
      rules: rules({
        esLint: webpackConfig.esLint,
        lessLoaderOptions: webpackConfig.lessLoaderOptions
      })
    },
    resolve: resolve({
      extensions: webpackConfig.extensions,
      alias: webpackConfig.alias,
    }),
    optimization: {
      minimize: true,
      splitChunks: {
        chunks: 'async',
      }
    },
    plugins: [
      configPlugins.DllReferencePlugin,
      configPlugins.CopyWebpackPlugin,
      configPlugins.MiniCssExtractPlugin,
      // configPlugins.HtmlWebpackPlugin_prd,
      configPlugins.OptimizeCSSAssetsPlugin,
      configPlugins.MapWebpackPlugin,
      configPlugins.HashedModuleIdsPlugin,
      configPlugins.ProgressPlugin,
      webpackConfig.sendSourceMap && configPlugins.SendSourceMapWebpackPlugin,
      configPlugins.CleanWebpackPlugin,
      ...webpackConfig.plugins
    ].filter(v => !!v),
  }
}